
use anyhow::Result;
use hyper::{Request, Response, Client, body};
use hyper::client::HttpConnector;
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use std::borrow::Borrow;

use crate::miner::{JsonRpcResponse, JsonRpcError};
use crate::miner::types::TaskType;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Sector {
    pub number: u64,
    pub miner: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CallId {
    #[serde(rename(deserialize = "ID"))]
    pub id: String,
    pub sector: Sector,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SealWork {
    #[serde(rename(deserialize = "ID"))]
    pub id: CallId,
    pub sector: Sector,
    pub task: TaskType,
    pub run_wait: i32,
    pub start: String,
}

pub async fn query_jobs_from_miner(client: &Client<HttpConnector>, url: &str, token: &str) -> Result<JsonRpcResponse<HashMap<String, Vec<SealWork>>>>{
    let body = r#"
{
	"jsonrpc": "2.0",
	"method": "Filecoin.WorkerJobs",
	"params": [],
	"id": 1
}
"#;
    let auth = format!("Bearer {}", token);
    let body = body::Body::from(body);

    let request = Request::builder()
        .uri(url)
        .header("Authorization", auth)
        .body(body)?;

    let rsp = client.request(request).await?;
    if rsp.status().is_success() {
        let buf = body::to_bytes(rsp).await?;
        let result: JsonRpcResponse<HashMap<String, Vec<SealWork>>> = serde_json::from_slice(buf.borrow())?;
        Ok(result)
    } else {
        Err(anyhow::Error::msg(format!("http request got error response {}", rsp.status())))
    }
}